package com.ruicar.afs.cloud.risk.tortoise.components;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruicar.afs.cloud.risk.api.dto.tortoise.TortoiseQueryBean;
import com.ruicar.afs.cloud.risk.api.enums.tortoise.GwtTortoiseScene;
import com.ruicar.afs.cloud.risk.tortoise.dto.notice.GwtTortoiseReq;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Author Peng Jinbo
 * @Date 2020/07/31 20:36
 */
@Component
@AllArgsConstructor
@Slf4j
@Getter
public class GwtTortoiseStrRedis {

    /**
     * String redis template
     */
    private final StringRedisTemplate stringRedisTemplate;

    /**
     * Author Peng Jinbo
     * Default expire set *
     *
     * @param data data
     */
    public void defaultExpireSet(TortoiseQueryBean data) {
        stringRedisTemplate.opsForValue().setIfAbsent(String.format("%s-%s", data.getMainId(), data.getScene()), JSON.toJSONString(data),
                1, TimeUnit.MINUTES);
    }

    /**
     * Author Peng Jinbo
     * Has boolean
     *
     * @return the boolean
     */
    public boolean notHas(String mainId, GwtTortoiseScene scene){
        return !stringRedisTemplate.hasKey(String.format("%s-%s", mainId, scene));
    }

    /**
     * Author Peng Jinbo
     * Set *
     *
     * @param data data
     */
    public void set(TortoiseQueryBean data) {
        stringRedisTemplate.opsForValue().set(String.format("%s-%s", data.getMainId(), data.getScene()), JSON.toJSONString(data), 2, TimeUnit.HOURS);
    }

    /**
     * Author Peng Jinbo
     * Get string
     *
     * @param req req
     * @return the string
     */
    public String get(GwtTortoiseReq req) {
        return stringRedisTemplate.opsForValue().get(String.format("%s-%s", req.getCaMainId(), req.getSceneCode()));
    }

    /**
     * Author Peng Jinbo
     * Assert get t
     *
     * @param <T>       parameter
     * @param req       req
     * @param entityClz entity clz
     * @return the t
     */
    public <T> T assertGet(GwtTortoiseReq req, Class<T> entityClz) {
        Assert.isTrue(stringRedisTemplate.hasKey(String.format("%s-%s", req.getCaMainId(), req.getSceneCode())), "业务数据不存在，操作失败。mainId :" + req.getCaMainId() + "，场景号：" + req.getSceneCode());
        return JSONObject.parseObject(get(req), entityClz);
    }

    /**
     * Author Peng Jinbo
     * Delay 1 minute clear *
     *
     * @param req req
     */
    public void delayClear(GwtTortoiseReq req) {
        log.info("业务数据清理，CaMaid : {}, Scene : {}, SerialNumber: {}",req.getCaMainId(),req.getSceneCode(),req.getSysCallLogId());
        stringRedisTemplate.expire(String.format("%s-%s", req.getCaMainId(), req.getSceneCode()), 1, TimeUnit.MINUTES);
    }

}
